/**
 * 准备函数
 */
var operateRight = new Object();
$(document).ready(function() {
	
	// 加载权限
	loadRole();

	// 加载表格
	queryUser();

	// 绑定函数
	$("#queryButton").bind("click", confirmQueryUser);
	$("#createButton").bind("click", showCreateUserDialog);
	$("#confirmCreateButton").bind("click", confirmCreateUser);
	$("#confirmModifyButton").bind("click", confirmModifyUser);
	$("#confirmResetPassword").bind("click", resetPassword);
});

/**
 * 加载权限
 */
function loadRole() {
	operateRight.modifyRight = $("#modify").val();
	operateRight.deleteRight = $("#delete").val();
}

/**
 * 查询用户
 */
function queryUser(pageIndex, pageSize) {
	// 组装参数
	var data = {};
	var name = $.trim($("#name").val());
	if (name != "") {
		data['name'] = name;
	}
	var status = $.trim($("#status").val());
	if (status != "") {
		data['status'] = status;
	}
	
	// 设置分页参数
	setPageIndex(data, pageIndex, pageSize);
	
	// 调用接口
	var response = callInterface("post", "user/queryUser", data, false);
	if (response.code == 0) {
		// 清空表格及分页
		$("#userTable tr:not(:first)").remove();
		$("#pageDiv").html("");

		var count = response.data.totalCount;
		if (count == null || count == 0) {
			// 获取表格行数、列数
			var trs = $("#userTable").find("tr").length;
			var cols = $("#userTable").find("tr:first th");
			$('#userTable').append("<tr><td colspan='" + cols.length + "'>无数据!</td></tr>");
			return false;
		}

		// 得到总页数
		var list = response.data.list;
		if (list != null && list.length > 0) {
			for ( var i in list) {
				var trHtml = "<tr>";
				trHtml += "<td align='center'>" + list[i].username + "</td>";
				trHtml += "<td align='center'>" + list[i].roleName + "</td>";
				trHtml += "<td align='center'>" + handleEmptyStr(list[i].name) + "</td>";
				trHtml += "<td align='center'>" + handleEmptyStr(list[i].phone) + "</td>";
				trHtml += "<td align='center'>" + handleEmptyStr(list[i].email) + "</td>";
				trHtml += "<td align='center'><input id='user_status_"+list[i].id+"' class='ace ace-switch' type='checkbox' "+ 
					(list[i].status == 1? 'checked': '')+" onclick='modifyUserStatus(" + list[i].id + ");' /> <span class='lbl'></span></td>";
				trHtml += "<td align='center'>" + list[i].createdTime + "</td>";
				// 操作
				trHtml += "<td align='center' class='operationColumn'>";
				if (operateRight.modifyRight == 1) {
					trHtml += "<a href='javascript:void(0);' class='edit' onclick='showModifyUserDialog(" + JSON.stringify(list[i]) + ");'>编辑</a>&nbsp;&nbsp;";
				}
				if (operateRight.deleteRight == 1) {
					trHtml += "<a href='javascript:void(0);' class='delete' onclick='deleteUser(" + list[i].id
							+ ",\"" + list[i].name + "\");'>删除</a>";
				}
				trHtml += "</td>";
				trHtml += "</tr>";

				// 动态添加一行
				$('#userTable').append(trHtml);
			}
		}

		// 调用分页
		layui.use(['laypage'], function() {
			var laypage = layui.laypage;
			laypage.render({
				elem : 'pageDiv',
				// pages : pages,
				curr : pageIndex || 1, // 当前页
				count : count,
				limit : pageSize,
				skip : true, // 是否开启跳页
				layout : ['count', 'prev', 'page', 'next', 'limit', 'skip'],
				groups : 5, // 连续显示分页数
				jump : function(obj, first) {
					if (!first) {
						queryUser(obj.curr, obj.limit);
					}
				}
			});
		});
	}else {
		showErrorMsg(response.code, response.message);
	}
}

/**
 * 确认查询
 */
function confirmQueryUser() {
	queryUser();
}

/**
 * 设置启用禁用
 */
function modifyUserStatus(id) {
	var data = {};
	var status = 0;
	if($('#user_status_'+id).is(":checked")){
		status = 1;
	}
	data.id = id;
	data.status = status;
	
	// 调用接口
	var response = callInterface("post", "user/updateUserStatus", data, false);
	if (response.code == 0) {
		showMsg('操作成功!');
	} else {
		showErrorMsg(response.code, response.message);
	}
	return false;
}

/**
 * 显示创建对话框
 */
function showCreateUserDialog() {
	// 弹出框
	$("#createUserDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#addUserForm')[0].reset();
	$("#cRoleId").val("");
	updateLayuiForm();
}

/**
 * 确认创建
 */
function confirmCreateUser() {
	// 获取参数
	var data = {};
	
	var roleId = $("#cRoleId").val();
	if (Utils.isNull(roleId)) {
		showAlert("请选择角色!");
		return;
	}
	data['roleId'] = roleId;
	
	var username = $.trim($('#cUsername').val());
	if (!/^[0-9a-zA-Z_]+$/.test(username)) {
		showAlert('用户名为字母、数字、下划线!');
		return;
	}else if(username == ""){
		showAlert('用户名不能为空!');
		return;
	}
	data['username'] = username;
	
	var password = $.trim($('#cPassword').val());
	if (Utils.isNull(password)) {
		showAlert('密码不能为空!');
		return;
	}
	
	var chkpwd = $.trim($('#cChkpwd').val());
	if (Utils.isNull(chkpwd)) {
		showAlert('确认密码不能为空!');
		return;
	}
	
	if (password != chkpwd) {
		showAlert('两次输入密码不一致!');
		return;
	}
	data['password'] = $.md5(password);
	
	var name = $.trim($('#cName').val());
	if (Utils.isNull(name)) {
		showAlert('用户姓名不能为空!');
		return;
	}
	data['name'] = name;
	
	var telephone = $.trim($('#cPhone').val());
	if (Utils.isNull(telephone)) {
		showAlert("手机号不能为空!");
		return false;
	}
	else if (telephone.length != 11) {
		showAlert("手机号格式不正确，请检查!");
		return false;
	}
	data['phone'] = telephone;
	
	data['email'] = $.trim($('#cEmail').val());
	data['status'] = 1;// 状态(0:禁用;1:启用)

	// 调用接口
	var response = callInterface("post", "user/createUser", data, false);
	if (response.code == 0) {
		showMsg('操作成功!');
		$('#createUserDialog').modal("hide");

		// 刷新
		queryUser();
	}
	else {
		showErrorMsg(response.code, response.message);
	}
}

/**
 * 显示修改用户对话框
 */
function showModifyUserDialog(data) {
	// 显示对话框
	$("#modifyUserDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#modifyUserForm')[0].reset();
	
	// 设置参数
	$("#mId").val(data.id);
	$("#mUsername").html(data.username);
	$("#mRoleName").html(data.roleName);
	$("#mRoleId").val(data.roleId);
	$("#mName").val(data.name);
	$("#mPhone").val(data.phone);
	$("#mEmail").val(data.email);
	$("#mStatus").val(data.status);
	updateLayuiForm();
}

/**
 * 确认修改用户
 */
function confirmModifyUser() {
	
	// 获取参数
	var data = {};
	data['id'] = $.trim($("#mId").val());
	var roleId = $.trim($('#mRoleId').val());
	data['roleId'] = roleId;
	
	var name = $.trim($('#mName').val());
	if (Utils.isNull(name)) {
		showAlert('真实姓名不能为空!');
		return;
	}
	data['name'] = name;
	
	var telephone = $.trim($("#mPhone").val());
	if (Utils.isNull(telephone)) {
		showAlert("手机号不能为空!");
		return false;
	}
	else if (telephone.length != 11) {
		showAlert("手机号格式不正确，请检查!");
		return false;
	}
	data['phone'] = telephone;
	data['email'] = $.trim($('#mEmail').val());
	data['status'] = $.trim($('#mStatus').val());
	
	// 调用接口
	var response = callInterface("post", "user/modifyUser", data, false);
	if (response.code == 0) {
		showMsg('操作成功!');
		$('#modifyUserDialog').modal("hide");

		// 刷新
		queryUser(currPage);
	}
	else {
		showErrorMsg(response.code, response.message);
	}
}

/**
 * 删除
 */
function deleteUser($id, $name) {
	// 设置参数
	var $data = {
		"id" : $id
	};

	// 询问框
	layer.confirm('确定删除[' + $name + ']吗？', {
		offset :'20px',btn: ['确定','取消']
	// 按钮
	}, function() {
		// 调用接口
		var response = callInterface("post", "user/deleteUser", $data, false);
		if (response.code == 0) {
			showMsg('操作成功!');

			// 刷新
			queryUser();
		}
		else {
			showErrorMsg(response.code, response.message);
		}
	}, function() {
		return;
	});
}